package cn.relx.basic.util;

import cn.relx.basic.config.BussinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Component
public class EmailUtil {
    // 注入邮件对象
    @Autowired
    private JavaMailSender javaMailSender;

    private static EmailUtil emailUtil;

    @PostConstruct
    private void init(){
        emailUtil = this;
        emailUtil.javaMailSender = this.javaMailSender;
    }

    public static void Email(String email,String text,String head){
        try {
            // 1.创建复杂邮件对象
            MimeMessage mimeMessage = emailUtil.javaMailSender.createMimeMessage();
            // 2.发送复杂邮件的工具类
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("a932984913@vip.qq.com");
            helper.setSubject(head);
            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
            helper.setText(text,true);
            // 4.添加附件
//            helper.addAttachment("20221015212731.jpg",new File("C:\\Users\\a9329\\Desktop\\20221015212731.jpg"));
            // 5.设置收件人
            helper.setTo(email);
            // 6.发送邮件
            emailUtil.javaMailSender.send(mimeMessage);
        } catch (MessagingException e){
            e.printStackTrace();
            throw new BussinessException("发送邮件失败!");
        }

    }

}
